package com.pn.serviceimpl;

import com.pn.entity.User;
import com.pn.mapper.UserMapper;
import com.pn.util.ResponseMsg;
import com.pn.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public User getByPrimaryKey(Integer uid) {
        return userMapper.getByPrimaryKey(uid);
    }

    @Override
    public User getByPhone(String phone) {
        System.out.println("正在从数据库查询数据");
        return userMapper.getByPhone(phone);
    }

    /**
     * 验证注册信息是否已经被注册
     * @param user
     * @return 200：注册成功
     *          50：用户名已经被注册
     *         100：其他错误
     */
    @Override
    public ResponseMsg insertNewUser(User user) {
        System.out.println("正在核验注册信息...");
        ResponseMsg resp = new ResponseMsg();
        User finder = this.getByPhone(user.getPhone());
        if (finder != null && finder.getPhone().equals(user.getPhone())) {
            resp.setRespStatusCode(50);
            resp.setRespMsg("用户名已被注册！");
            return resp;
        } else {
            user.setFirstIn(new Date());
            user.setLastIn(new Date());
            int insertedLine = userMapper.insertSelective(user);
            if(insertedLine == 1){
                resp.setRespStatusCode(200);
                resp.setRespMsg("注册成功！");
                return resp;
            }
        }
        resp.setRespStatusCode(100);
        resp.setRespMsg("服务器错误！请稍后重试");
        return resp;
    }

    @Override
    public int updateLast_inByPhone(String phone) {
        User tempU = new User();
        tempU.setPhone(phone);
        tempU.setLastIn(new Date());
        return userMapper.updateByPhoneSelective(tempU);
    }

    /**
     * 验证登录信息
     * @param user
     * @return  200:登录成功！
     *          0:不存在手机号
     *          300:手机号或密码错误
     */
    @Override
    public ResponseMsg checkLoginInfo(User user) {
        System.out.println("正在对用户信息进行校验...");
        User finder = this.getByPhone(user.getPhone());
        System.out.println("查到的用户信息为：" +finder);
        ResponseMsg resp = new ResponseMsg();
        if(finder!=null && finder.getPwd().equals(user.getPwd())){
            resp.setRespStatusCode(200);
            resp.setRespMsg("登录成功！");
            return resp;
        } else{
            if(finder == null){
                resp.setRespStatusCode(0);
                resp.setRespMsg("不存在该手机号，请核查！");
                return resp;
            } else {
                resp.setRespStatusCode(300);
                resp.setRespMsg("手机号或密码错误！");
                return resp;
            }
        }
    }

    @Override
    public ResponseMsg checkUserInCache(User user) {
        return null;
    }

    @Override
    public ResponseMsg addUserInCache(User user) {
        return null;
    }
}
